#include "monitor.h"

int mon_row = 0, mon_col = 0;
unsigned short *vidmem = (unsigned short*)0xB8000;

int vga_init()
{
	/*
	 * Set up framebuffer, VGA mode
	 */
	return -1; //Doen't work yet
}

int scroll(int lines)
{
	int i = 0;
	int j = 0;
	/*
	 * Moves the contents of every line variable lines times up.
	 */
	while(i < ((MON_HEIGHT-lines)*MON_WIDTH))
	{
		vidmem[i] = vidmem[i+(MON_WIDTH*lines)];
		i++;
	}
	while(i<MON_HEIGHT*MON_WIDTH)
	{
		vidmem[i] = 0xF020;
		i++;
	}
	
	return 0; // Works
}

int clear()
{
	/*
	 * Put a space character to every character on screen
	 */
	unsigned short *location;
	int i = 0;
	while (i < MON_HEIGHT*MON_WIDTH)
	{
		location = vidmem+i;
		*location = 0xFF20;
		i++;
	}
	return 0;
}

int putc(unsigned char chr)
{
	/*
	 * TODO: Print a character to next location, if next location is out of bounds, get back in bounds.
	 */
	short tobeset = 0;
	if ((mon_col >= MON_WIDTH) || (chr == '\n'))
	{
		mon_col = 0;
		if (mon_row >= MON_HEIGHT)
		{
			scroll(1);
		} else {
			mon_row++;
		}
		if (chr == '\n')
			return 0;
	} else {
		mon_col++;
	}

	unsigned char color = (0xF << 4) | (0x0 & 0x0F);
	vidmem[mon_row*MON_WIDTH+(mon_col-1)] = chr | (color << 8);
	
	/*
	 * TODO: 
	 */

	return 0; //DOES WORK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}

int printf(char* string)
{
	/*
	 * TODO: Prints a string to stdout
	 */
	int i = 0;
	while (string[i] != 0)
	{
		putc(string[i++]);
	}

	return -1; //Doen't work yet
}

char hex[16] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

int printhex(unsigned int n)
{
	printf("0x");
	int i = 7;
	while (( (( n >> 4*i ) & 0xf) == 0x0)&(i>0)) {
		i--;
	}
	while (i>=0) {
		putc(hex[( n >> 4*i ) & 0xf]);
		i--;
	}
}
